package com.springcloud_consumer.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @author: wu linchun
 * @time: 2021/9/16 17:32
 * @description:
 */
@Controller
@RequestMapping("consumer")
public class ConsumerController {
    //RestTemplate已经在配置类中变成了一个bean
    @Autowired  //RestTemplate提供多种便捷访问远程http服务的方法，简单的restful服务模板
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    private static final String REST_URL_PREFIX = "http://MYSPRINGCLOUD-PROVIDER";

    @GetMapping("c1")
    @ResponseBody
    public Object PrintAll() {
//        ResponseEntity<List> responseEntity = restTemplate.exchange("http://127.0.0.1:8082/index/getAll",
//                HttpMethod.GET, null, List.class);
        ResponseEntity<List> responseEntity = restTemplate.exchange(REST_URL_PREFIX + "/index/getAll",
                HttpMethod.GET, null, List.class);
        System.out.println("返回的请求体为：" + responseEntity.getBody());
        return responseEntity.getBody();
    }


    //注册进来的微服务，获取一些消息~
    @GetMapping("discovery")
    @ResponseBody
    public Object discovery() {
        //获取微服务列表的清单
        List<String> services = discoveryClient.getServices();
        System.out.println("discovery=>services：" + services);

        //得到一个具体的微服务信息，通过具体的微服务id，applica  springcloud-consumer_8083
        List<ServiceInstance> instances = discoveryClient.getInstances("Myspringcloud-consumer_8083");
        for (ServiceInstance instance : instances) {
            System.out.println(instance.getHost() + "\t" +
                    instance.getPort() + "\t" + instance.getUri() + "\t" + instance.getServiceId());
        }
        return this.discoveryClient;
    }

    @GetMapping("/testGroup")
    @ResponseBody
    public Object testGroup() {
        ResponseEntity<String> responseEntity = restTemplate.exchange(REST_URL_PREFIX + "/index/testGroup",
                HttpMethod.GET, null, String.class);
        return responseEntity.getBody();
    }

}
